﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;

namespace NHINDirect
{
    public class UniformTrustSettings : ITrustSettingsStore
    {
        X509Certificate2Collection m_anchors;
        
        public UniformTrustSettings(IX509Store anchorStore)
        {
            if (anchorStore == null)
            {
                throw new ArgumentNullException();
            }
            X509Certificate2Collection anchors = new X509Certificate2Collection();
            anchors.Add(anchorStore.GetCertificates());
            
            this.Anchors = anchors;
        }
        
        public UniformTrustSettings(X509Certificate2 anchor)
            : this(new X509Certificate2Collection(anchor))
        {
        }

        public UniformTrustSettings(X509Certificate2Collection anchors)
        {
            this.Anchors = anchors;
        }
        
        public X509Certificate2Collection Anchors
        {
            get
            {
                return this.m_anchors;
            }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException();
                }

                this.m_anchors = value;
            }
        }

        public X509Certificate2Collection GetTrustAnchorsIncoming(MailAddress address)
        {
            return this.m_anchors;
        }

        public X509Certificate2Collection GetTrustAnchorsOutgoing(MailAddress address)
        {
            return this.m_anchors;
        }
        
        /// <summary>
        /// Loads certificates from a LocalMachine Certificate store named "NHINAnchors"
        /// </summary>
        public static UniformTrustSettings Create()
        {
            using (SystemX509Store store = SystemX509Store.OpenAnchor())
            {
                return new UniformTrustSettings(store);
            }
        }
    }
}
